package com.nova.bluetooth.helpUtils;

import android.text.format.DateUtils;

import androidx.annotation.NonNull;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

public class DateUtil {

    private static final DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
    private static final Calendar calendar = Calendar.getInstance();

    public static final String Y_M_D = "yyyy-MM-dd";
    public static final String Y_POINT_M_POINT_D = "yyyy.MM.dd";
    public static final String Y_L_M_L_D = "yyyy/MM/dd";
    public static final String Y_M = "yyyy-MM";
    public static final String Y_T_M_T = "yyyy年MM月";
    public static final String Y_M_D_H_M = "yyyy-MM-dd HH:mm";
    public static final String M_T_D_T_H_M = "MM月dd日 HH:mm";
    public static final String Y_M_D_H_M_S = "yyyy-MM-dd HH:mm:ss";

    public static final String Y_T_M_T_D_T_H_M = "yyyy年MM月dd日 HH:mm";
    public static final String Y_T_M_T_D_T_H_M_en = "yyyy-MM-dd HH:mm";

    public static final String M_POINT_D = "MM.dd";
    public static final String M_S = "mm:ss";
    public static final String M_S_C = "mm分ss秒";
    public static final String H_M_S = "HH:mm:ss";
    public static final String H_M = "HH:mm";
    public static final String M_L_D = "MM/dd";

    public static final String TARGET_TIME_STR = "2024-08-01";  // 目标日期-在此之前的设备判定为旧设备，部分协议的功能不支持

    public static boolean isCurrentAfterTarget(String currentTimeStr) {
        if (currentTimeStr == null) return false;
        return !isCurrentBeforeTarget(currentTimeStr, TARGET_TIME_STR);
    }


    /**
     * 将日期字符串解析为 "yyyy-MM-dd" 格式的字符串
     *
     * @param dateString 日期字符串，格式为 "yyyy-MM-dd HH:mm:ss"
     * @return 格式化后的日期字符串
     * @throws ParseException 如果日期字符串格式不正确
     */
    public static String formatDateToYMD(String dateString) {
        Date date = null;
        try {
            date = df.parse(dateString);
        } catch (ParseException e) {
            LogUtil.e(e.toString());
        }
        return df2.format(date);
    }


    /**
     * 比较当前日期是否在给定日期之前。
     *
     * @param currentTimeStr 当前时间字符串，格式为 "yyyy-MM-dd"
     * @param targetTimeStr  要判断的时间字符串，格式为 "yyyy-MM-dd"
     * @return 如果当前日期在给定日期之前返回 true，否则返回 false
     */
    private static boolean isCurrentBeforeTarget(String currentTimeStr, String targetTimeStr) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date currentDate = sdf.parse(currentTimeStr);
            Date targetDate = sdf.parse(targetTimeStr);
            return currentDate.before(targetDate);
        } catch (ParseException e) {
            // 处理日期解析错误的情况
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 返回当前时间
     *
     * @return
     */
    public static String getTime() {
        Date date = new Date();
        String format = df.format(date);
        return format;
    }

    /**
     * 获取两个时间差值 几天几时几分几秒
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public static String dateDifference(String startTime, String endTime) {
        String str = "";
        try {
            Date start = df.parse(startTime);
            Date end = df.parse(endTime);
            //除以1000是为了转换成秒
            long between = (end.getTime() - start.getTime()) / 1000;
            long day = between / (24 * 3600);
            long hour = between % (24 * 3600) / 3600;
            long minute = between % 3600 / 60;
            long second = between % 60;
            System.out.println(between % 60);
            str = day + "天" + hour + "小时" + minute + "分" + second + "秒";
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return str;
    }

    public static long secondDifference(String startTime, String endTime) {
        long s = 0L;
        try {
            DateFormat format = new SimpleDateFormat(DateUtil.Y_M_D_H_M_S);
            Date start = format.parse(startTime);
            Date end = format.parse(endTime);
            s = (end.getTime() - start.getTime()) / 1000;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return s;
    }


    public static String reYearSun(String date, int day) {
        try {
            calendar.setTime(df2.parse(date));
            calendar.add(Calendar.YEAR, day);
            return df2.format(calendar.getTime());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String reWeekSun(String date, int day) {
        try {
            calendar.setTime(df2.parse(date));
            calendar.add(Calendar.WEEK_OF_YEAR, day);
            return df2.format(calendar.getTime());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 返回当前时间之前N周 本周 之后N周 的周一周日准确时间
     *
     * @param date 当前时间
     * @param week 获取上几周就传负数几 下几周就正数＋1  举例上周 传 -1 本周传 0 下周传 1
     * @return
     */
    public static Map<String, String> reMonSun(String date, int week) {
        Map<String, String> map = new HashMap();

        try {
            calendar.setTime(df2.parse(date));
            //设置一周第一天是星期一  国外的一周第一天是星期天 默认是按照国外算得
            calendar.setFirstDayOfWeek(Calendar.MONDAY);

            calendar.add(Calendar.WEEK_OF_MONTH, week);

            //查询当前星期几 在本周中 从周日开始算 星期天就是 1 星期一就是2 以此类推
            int nowTime = calendar.get(Calendar.DAY_OF_WEEK);
            //是1的时候就是星期天 给他赋值8 可以在下边得出负数 用于消减时间 其他状况不做处理
            if (nowTime == 1) {
                nowTime = 8;
            }
            calendar.add(Calendar.DATE, calendar.getFirstDayOfWeek() - nowTime);
            Date monday = calendar.getTime();
            String weekBegin = df2.format(monday);
            // 此时日期已经是星期一 给当前日期加上6天必然是周末
            calendar.add(Calendar.DATE, 6);
            Date sundayDate = calendar.getTime();
            String weekEnd = df2.format(sundayDate);
            map.put("mondayDate", weekBegin);
            map.put("sundayDate", weekEnd);
            return map;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 返回当前时间之前N天 本天 之后N天 的一天日准确时间
     *
     * @param date 当前时间
     * @param day  获取上几天就传负数几 下几天就正数＋1  举例上天 传 -1 本天传 0 下天传 1
     * @return
     */
    public static String reDaySun(String date, int day) {
        try {
            calendar.setTime(df2.parse(date));
            calendar.add(Calendar.DATE, day);
            return df2.format(calendar.getTime());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 返回当前时间之前N天 本天 之后N天 的一天日准确时间
     *
     * @param dateFormatType 想要输出的时间类型
     * @param date           当前时间
     * @param day            获取上几天就传负数几 下几天就正数＋1  举例上天 传 -1 本天传 0 下天传 1
     * @return
     */
    public static String reDaySun(String date, int day, String dateFormatType) {
        DateFormat dateFormat = new SimpleDateFormat(dateFormatType);
        try {
            calendar.setTime(dateFormat.parse(date));
            calendar.add(Calendar.DATE, day);
            return dateFormat.format(calendar.getTime());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String reHourSun(String date, int time, String dateFormatType) {
        DateFormat dateFormat = new SimpleDateFormat(dateFormatType);
        try {
            calendar.setTime(dateFormat.parse(date));
            calendar.add(Calendar.HOUR, time);
            return dateFormat.format(calendar.getTime());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String reMinuteSun(String date, int day, String dateFormatType) {
        DateFormat dateFormat = new SimpleDateFormat(dateFormatType);
        try {
            calendar.setTime(dateFormat.parse(date));
            calendar.add(Calendar.MINUTE, day);
            return dateFormat.format(calendar.getTime());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 返回当前时间之前N月 本月 之后N月 的月准确时间
     *
     * @param date  当前时间
     * @param month 获取上几月就传负数几 下几月就正数＋1  举例上月 传 -1 本月传 0 下月传 1
     * @return
     */
    public static String reMonthSun(String date, int month) {
        try {
            calendar.setTime(df2.parse(date));
            calendar.add(Calendar.MONTH, month);
            return df2.format(calendar.getTime());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 返回当前时间之前N月 本月 之后N月第一天和最后一天
     *
     * @param date  当前时间
     * @param month 获取上几月就传负数几 下几月就正数＋1  举例上月 传 -1 本月传 0 下月传 1
     * @return
     */
    public static Map<String, String> reOneLast(String date, int month) {

        Map<String, String> map = new HashMap();
        try {
            calendar.setTime(df2.parse(date));
            //当前月的上个月
            calendar.add(Calendar.MONTH, month);
            //设置当前月的最大天数
            calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
            Date lastDateOfMonth = calendar.getTime();
            String lastDay = df2.format(lastDateOfMonth);
            //设置一 即为每月第一天
            calendar.set(Calendar.DATE, 1);
            Date oneDayofMonth = calendar.getTime();
            String oneDay = df2.format(oneDayofMonth);
            map.put("oneDay", oneDay);
            map.put("lastDay", lastDay);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return map;
    }

    /**
     * 返回当月最大天数
     *
     * @param date 当前时间
     * @return
     */
    public static int reMonthMaxDay(String date) {
        try {
            calendar.setTime(df2.parse(date));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int actualMaximum = calendar.getActualMaximum(Calendar.DATE);
        return actualMaximum;
    }


    /**
     * 时间字符串格式转换
     *
     * @param targetFormat 想要转换的格式
     * @param oldDate      数据源的格式
     * @return
     */
    public static String formatConversion(String oldFormat, String targetFormat, String oldDate) {
        DateFormat dateFormat = new SimpleDateFormat(targetFormat);
        try {
            DateFormat myDateFormat = new SimpleDateFormat(oldFormat);
            calendar.setTime(myDateFormat.parse(oldDate));
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (NullPointerException nullPointerException) {
            nullPointerException.printStackTrace();
        }
        return dateFormat.format(calendar.getTime());
    }

    public static String getDateToString(Date date, String pattern) {
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        return format.format(date);
    }

    /**
     * 时间戳转换成字符窜
     *
     * @param milSecond
     * @param pattern
     * @return
     */
    public static String getDateToString(long milSecond, String pattern) {
        Date date = new Date(milSecond);
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        return format.format(date);
    }

    /**
     * 时间戳转换成字符窜
     *
     * @param milSecond
     * @param pattern
     * @return
     */
    public static String getDateToString(long milSecond, String pattern, String timeZone) {
        Date date = new Date(milSecond);
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        format.setTimeZone(TimeZone.getTimeZone(timeZone));
        return format.format(date);
    }

    /**
     * 字符串 转换为 Date
     */
    public static Date getStringToDate(String dateString, String pattern) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);//根据自己情况
        Date date = sdf.parse(dateString); //String转Date
        return date;
    }

    /**
     * 时间字符串格式转换
     *
     * @param targetFormat
     * @param date
     * @return
     */
    public static String formatConversion(String targetFormat, String date) {
        DateFormat dateFormat = new SimpleDateFormat(targetFormat);
        try {
            calendar.setTime(df2.parse(date));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return dateFormat.format(calendar.getTime());
    }

    public static int formatGetMonth(String date) {
        DateFormat dateFormat = new SimpleDateFormat("MM");
        try {
            calendar.setTime(df2.parse(date));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return Integer.parseInt(dateFormat.format(calendar.getTime()));
    }


    //根据秒数转化为时分秒   00:00:00
    public static String secondToTime(int second) {
        if (second < 10) {
            return "00:00:0" + second;
        }
        if (second < 60) {
            return "00:00:" + second;
        }
        if (second < 3600) {
            int minute = second / 60;
            second = second - minute * 60;
            if (minute < 10) {
                if (second < 10) {
                    return "00:0" + minute + ":0" + second;
                }
                return "00:0" + minute + ":" + second;
            }
            if (second < 10) {
                return "00:" + minute + ":0" + second;
            }
            return "00:" + minute + ":" + second;
        }
        int hour = second / 3600;
        int minute = (second - hour * 3600) / 60;
        second = second - hour * 3600 - minute * 60;
        if (hour < 10) {
            if (minute < 10) {
                if (second < 10) {
                    return "0" + hour + ":0" + minute + ":0" + second;
                }
                return "0" + hour + ":0" + minute + ":" + second;
            }
            if (second < 10) {
                return "0" + hour + ":" + minute + ":0" + second;
            }
            return "0" + hour + ":" + minute + ":" + second;
        }
        if (minute < 10) {
            if (second < 10) {
                return hour + ":0" + minute + ":0" + second;
            }
            return hour + ":0" + minute + ":" + second;
        }
        if (second < 10) {
            return hour + ":" + minute + ":0" + second;
        }
        return hour + ":" + minute + ":" + second;
    }

    /**
     * 秒转换成 00'00'' 格式
     *
     * @param second 秒
     * @return
     */
    public static String secondToSpeed(long second) {
        /** 转换分钟 **/
        long minutes = second / 60;
        /** 剩余秒数 **/
        second = second % 60;
        return unitFormat(minutes) + "'" + unitFormat(second) + "''";
    }


    public static int getDaysOfMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    }


    private static String unitFormat(long i) {
        String retStr;
        if (i >= 0 && i < 10) {
            retStr = "0" + i;
        } else {
            retStr = "" + i;
        }
        return retStr;
    }

    public static void main(String[] args) {
        String date = "2020-11-05";
    }

    /**
     * 计算创建时间离15分钟还差多久
     *
     * @param createTime
     * @return
     */
    public static String getMinuteGapCurrent(@NonNull String createTime) {
        String pattern = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);

        try {
            Date time1 = dateFormat.parse(createTime);
            Date time2 = new Date();
            long l = time1.getTime() + 15 * 60 * 1000;
            long timeDifference = l - time2.getTime();
            if (timeDifference <= 0) {
                return "-1";
            } else {
                // 将差异转换为 mm:ss 格式
                long minutes = timeDifference / (60 * 1000);
                long seconds = (timeDifference / 1000) % 60;

                return String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "15:00";
    }

    /**
     * 判断给定日期距离当前时间的相对时间，如几分钟前、几小时前或几天前
     *
     * @param dateString
     * @return
     */
    public static String getRelativeTime(String dateString) {
        SimpleDateFormat format = new SimpleDateFormat(DateUtil.Y_M_D_H_M_S);
        try {
            Date date = format.parse(dateString);
            long timeInMillis = date.getTime();
            long currentTime = System.currentTimeMillis();

            CharSequence relativeTime = DateUtils.getRelativeTimeSpanString(timeInMillis, currentTime, DateUtils.MINUTE_IN_MILLIS);

            return relativeTime.toString();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return ""; // Return an empty string in case of an error
    }

    public static String secondToMinute(int second) {
        /** 转换分钟 **/
        long minutes = second / 60;
        /** 剩余秒数 **/
        second = second % 60;
        return unitFormat(minutes) + "分" + unitFormat(second) + "秒";
    }

    public static String secondToMinute(int second, String min, String send) {
        /** 转换分钟 **/
        long minutes = second / 60;
        /** 剩余秒数 **/
        second = second % 60;
        return unitFormat(minutes) + min + " " + unitFormat(second) + send;
    }
}
